package com.attilax.lang.mail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.json.AtiJson;
import com.attilax.lang.CmdX;


/**
 * com.attilax.lang.mail.MxScanner
 * @author Administrator
 *
 */
public class MxScanner {

	public static void main(String[] args) throws IOException {
		String f = pathx.classPathParent()+"\\dom.txt";
				//args[0].trim();
		
		String dir =pathx.classPathParent()+"\\result.txt";
				//+ " args[1].trim();
		List<String> domains = filex.read2list(f);
		filex fx = new filex(dir);
		for (String dom : domains) {
			try {
				String cmd = "nslookup -qt=mx  163.com";
				cmd = cmd.replaceAll("163.com", dom);
				String t = CmdX.exec(cmd);
				List<String> mxs = getMxs(t);
				
				for (String mx : mxs) {
					String lin_new=dom+"----"+mx;
					fx.appendLine_flush_safe(lin_new);
				}
			

				System.out.println(t);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		fx.close();
		System.out.println("--f");

	}

	private static List<String> getMxs(String lookupAfterRetTxt) {
		List<String> mxs = new ArrayList<String>();
		String[] lines = lookupAfterRetTxt.split("\n");
		for (String line : lines) {
			try {
				if (line.contains("MX preference")
						&& line.contains("mail exchanger")) {
					String[] a = line.split("=");
					String mx = a[a.length - 1].trim();
					mxs.add(mx);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return mxs;
	}

 
String domain;
	public MxScanner According_to_the_domain_name(String string) {
		domain=string;
		return this;
	}

	public MxScanner query_MX_records() {
		query_MX_records(this.domain);
		return this;
	}
	private MxScanner query_MX_records(String domain2) {
		String cmd = "nslookup -qt=mx  163.com";
		cmd = cmd.replaceAll("163.com", domain2);
		String t = CmdX.exec(cmd);
		List<String> mxs = getMxs(t);
		rzt=mxs;
		return this;
	}
	Object rzt;
	Object final_rzt;

	public MxScanner outputAsJson() {
		final_rzt= AtiJson.toJson(rzt);
		return this;
	}

	public void print() {
		System.out.println(this.final_rzt);
		
	}
}
